package com.magoldeditor.util.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.magoldeditor.at.MaEditorXMLException;

/**
 * 
 * @author Velconia
 * @version v.1.0
 * 
 */
public class ContentXMLReader extends MaEditorXMLReader implements IContentReader, Iterator<String> {
	
	/**
	 * iterator location
	 */
	private int location = 0;
	
	/**
	 * 
	 * @param fileName
	 * @throws FileNotFoundException
	 */
	public ContentXMLReader(String fileName) throws FileNotFoundException {
		super(fileName);
	}
	
	/**
	 * 
	 * @param file
	 * @throws FileNotFoundException
	 */
	public ContentXMLReader(File file) throws FileNotFoundException {
		super(file);
	}
	
	/**
	 * 
	 * @param fileInputStream
	 */
	public ContentXMLReader(FileInputStream fileInputStream) {
		super(fileInputStream);
	}

	@Override
	public String getContent(final String nodeName, final String attributeName) throws MaEditorXMLException {
		Node n1 = getContentNode(nodeName);
		if (n1 != null) {
			Node n2 = n1.getAttributes().getNamedItem(attributeName);
			if (n2 != null) return n2.getNodeValue();
			else throw new MaEditorXMLException("there is no such attr in xml file");
		} else throw new MaEditorXMLException("there is no such node in xml file");
	}

	@Override
	public int getIntContent(final String nodeName, final String attributeName) throws MaEditorXMLException {
		return Integer.parseInt(getContent(nodeName, attributeName));
	}
	
	@Override
	public double getDoubleContent(final String nodeName, final String attributeName) throws MaEditorXMLException {
		return Double.parseDouble(getContent(nodeName, attributeName));
	}
	
	@Override
	public Node getContentNode(final String nodeName) {
		return this.readNode(readList(), nodeName);
	}
	
	@Override
	public boolean hasNext() {
		if (location < this.readList().getLength()) return true;
		else return false;
	}

	@Override
	public String next() {
		NodeList nodeList = this.readList();
		
		if (location < nodeList.getLength()) {
			String s = nodeList.item(location++).getNodeName();
			if (!s.equals("#text")) return s;
			else return null;
		} else {
			return null;
		}
	}
	
	@Override
	public void remove() {
		location++;
	}
}
